package w83b.w83bUtilidades;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.validator.Field;
import org.apache.commons.validator.GenericValidator;
import org.apache.commons.validator.Validator;
import org.apache.commons.validator.ValidatorAction;
import org.apache.commons.validator.ValidatorUtil;
import org.apache.struts.action.ActionErrors;

import w83b.w83bUtilidadesComunes.W83bClsConstantes;
import w83b.w83bUtilidadesComunes.W83bDateUtil;
import es.ejie.frmk.listeners.base.Q70ListenerUtils;
import es.ejie.frmk.presentacion.validacion.Q70ValidacionesCampo;
import es.ejie.frmk.presentacion.validacion.Q70ValidacionesGenericas;

/**
 * 
 * @author 
 *
 */
public class W83bValidarGeremua extends Q70ValidacionesGenericas {
	private W83bValidarGeremua(){
		
	}

    public static String validarFechaMenor(Object bean, ValidatorAction va, Field field, ActionErrors errors, Validator validator, HttpServletRequest request)
    {
    	String str1 = null;
    	
    	if (isString(bean)){
  	      str1 = (String)bean;
	  	}else {
	  	  str1 = ValidatorUtil.getValueAsString(bean, field.getProperty());
	  	}
    	
    	Object form = validator.getResource(Validator.BEAN_KEY);
        String dependProp = field.getVarValue("fechaHasta");
        String str2 = ValidatorUtil.getValueAsString(form, dependProp);
        String strIdioma = Q70ListenerUtils.getLanguage(request);
	  	
        try{
		    if(StringUtils.isNotEmpty(str1)
		    		&&StringUtils.isNotEmpty(str2)){
		    	//ver si son dates
		    	str1 = W83bDateUtil.getInstance().rellenarConCerosDate(str1,strIdioma);//NOPMD
		    	str2 = W83bDateUtil.getInstance().rellenarConCerosDate(str2,strIdioma);//NOPMD
		    	boolean str1Valido = fncValidarFecha(str1,strIdioma);
		    	boolean str2Valido = fncValidarFecha(str2,strIdioma);
		    	if(str1Valido
		    			&&str2Valido){
		    		List list1 = W83bDateUtil.getInstance().separarDiaMesAnyo(str1,strIdioma);
		    		List list2 = W83bDateUtil.getInstance().separarDiaMesAnyo(str2,strIdioma);
		    		int anyoDesde = Integer.parseInt((String)list1.get(2));
		    		int mesDesde  = Integer.parseInt((String)list1.get(1));;
		    		int diaDesde  = Integer.parseInt((String)list1.get(0));;
		    		int anyoHasta  = Integer.parseInt((String)list2.get(2));;
		    		int mesHasta  = Integer.parseInt((String)list2.get(1));;
		    		int diaHasta  = Integer.parseInt((String)list2.get(0));;
		    		
		    		boolean resultado = false;
		    		
		    		if(anyoDesde<=anyoHasta){
		    			if(mesDesde<=mesHasta){
		    				if(diaDesde<=diaHasta){
		    					resultado = true;
		    				}	    				
		    			}	    				
		    		}
		    		
		    		if(!resultado){
		    			errors.add(field.getKey(), Q70ValidacionesCampo.getActionError(request, va, field));
		    		}
		    		
		    	}
		    }
        }catch (Exception e) {
			// TODO: handle exception
        	errors.add(field.getKey(), Q70ValidacionesCampo.getActionError(request, va, field));
		}
	  	

        return str1;
    }   
    
    
    /**
     * Checks if the field matches the boolean expression specified in
     * <code>test</code> parameter.
     *
     * @param bean    The bean validation is being performed on.
     * @param va      The <code>ValidatorAction</code> that is currently being
     * performed.
     * @param field   The <code>Field</code> object associated with the
     * current field being validated.
     * @param errors  The <code>ActionErrors</code> object to add errors to
     * if any validation errors occur.
     * @param validator the validator
     * @param request Current request object.
     * @return  if meets stated requirements,
     *  otherwise.
     */
    public  boolean validateDate(Object bean, ValidatorAction va,
        Field field, ActionErrors  errors, Validator validator,
        HttpServletRequest request) { 
    	boolean valido=false;       	
    	valido=this.validateDate(bean, va, field, errors, validator, request);
    	return valido;
    }
    
 /**
  * Checks if is string.
  *
  * @param paramObject the param object
  * @return true, if is string
  */
 protected static boolean isString(Object paramObject){
    return ((paramObject == null) ? true : String.class.isInstance(paramObject));
  }
    
    /**
     * Validate date.
     *
     * @param bean the bean
     * @param va the va
     * @param field the field
     * @param errors the errors
     * @param request the request
     * @return the date
     */
    public static Date validateDate(Object bean, ValidatorAction va,
			Field field, ActionErrors errors, HttpServletRequest request) {
    	Date localDate = null;
    	String str1 = null;
    	
    	if (isString(bean)){
    	      str1 = (String)bean;
    	}else {
    	      str1 = ValidatorUtil.getValueAsString(bean, field.getProperty());
    	}
    	
    	String strIdioma = Q70ListenerUtils.getLanguage(request);
    	     
    	boolean resultado = false;
    
        if (!(GenericValidator.isBlankOrNull(str1))) {
        	
	        try {
	            
	        	resultado = fncValidarFecha(str1,strIdioma);
	        	
	        	if(resultado){
	        		localDate = W83bDateUtil.getInstance().stringToDateIdioma(str1,strIdioma);
	        	}
	        	
	          }catch (Exception localException) {
	        	  localDate = null;
	    	   }
	    	 
	    	   if (!resultado) {
	    		   errors.add(field.getKey(), Q70ValidacionesCampo.getActionError(request, va, field));
	    	   }
    	   }
    	
    	    return localDate;
	}
    
    /**
     * Validate date.
     *
     * @param bean the bean
     * @param va the va
     * @param field the field
     * @param errors the errors
     * @param request the request
     * @return the date
     */
    public static boolean validateDni(Object bean, ValidatorAction va, Field field, ActionErrors errors, Validator validator, HttpServletRequest request){
    	
    	String str1 = null;
    	
    	if (isString(bean)){
    	      str1 = (String)bean;
    	}else {
    	      str1 = ValidatorUtil.getValueAsString(bean, field.getProperty());
    	}
    	
    	     
    	boolean resultado = false;
    
        if (!(GenericValidator.isBlankOrNull(str1))) {
        	
	        try {	            
	        	resultado = W83bUtilidadesComunes.fncValidarDni(str1);	        	
	        	
	          }catch (Exception localException) {
	        	  resultado = false;
	        	  return resultado;
	    	   }	    	 
	    	   if (!resultado) {
	    		   errors.add(field.getKey(), Q70ValidacionesCampo.getActionError(request, va, field));
	    	   }
    	   }   	
        return resultado;
	}

    /**
     * Fnc validar fecha.
     *
     * @param strPfValor the str pf valor
     * @param idioma the idioma
     * @return true, if successful
     */
    public static boolean fncValidarFecha(String strPfValor,String idioma) {
        boolean bolRetorno = true;
        try {
        	
        	int intAnyo = 0;
        	int intMes = 0;
        	int intDia = 0;
        	if(W83bClsConstantes.CONSTANTE_EUSKARA.equals(idioma)){
	            intAnyo = Integer.parseInt(strPfValor.substring(0, 4));
	            intMes = Integer.parseInt(strPfValor.substring(5, 7));
	            intDia = Integer.parseInt(strPfValor.substring(8, 10));
        	}else{            
	            intAnyo = Integer.parseInt(strPfValor.substring(6, 10));
	            intMes = Integer.parseInt(strPfValor.substring(3, 5));
	            intDia = Integer.parseInt(strPfValor.substring(0, 2));
        	}

            if (intMes < 1 || intMes > 12) {
                return false;
            } else if (!(intMes < 1 || intMes > 12)) {
                int intDiasMes = W83bDateUtil.getInstance().calculaDias(intAnyo, intMes);
                
                if (intDia < 1 || intDia > 31 || intDia > intDiasMes) {
                    return false;
                } else if (intAnyo == 0) {
                    return false;
                }
            }

        } catch (Exception e) {  
            bolRetorno = false;
            return bolRetorno;
        }
        return bolRetorno;
    }


public static boolean validateRequiredOne(Object bean, ValidatorAction va, Field field, ActionErrors errors, Validator validator, HttpServletRequest request)
{
	String str1;
	if (isString(bean)){
	      str1 = (String)bean;
	}else {
	      str1 = ValidatorUtil.getValueAsString(bean, field.getProperty());
	}
     
	int j = 0;
	
	boolean noVacio = false;
    
	Object form = validator.getResource(Validator.BEAN_KEY);
	
	if(StringUtils.isEmpty(str1)){
	      while (!GenericValidator.isBlankOrNull(field.getVarValue("field[" + j + "]"))) {
		      String str3 = field.getVarValue("field[" + j + "]");
		      String value = ValidatorUtil.getValueAsString(form, str3);
		      if(!StringUtils.isEmpty(value)){
		    	  noVacio = true;
		    	  break;	    	  
		      }	     
		       j++;		
	      }
     }else{
    	 noVacio = true;
     }
     
	  if(!noVacio){
		  errors.add(field.getKey(), Q70ValidacionesCampo.getActionError(request, va, field));
		  return false;	  
	  } else{
		  return true;
		  
	  }
     
  }

/**
 * Validate telefono.
 *
 * @param bean the bean
 * @param va the va
 * @param field the field
 * @param errors the errors
 * @param request the request
 * @return the date
 */
public static boolean validateTelefono(Object bean, ValidatorAction va, Field field, ActionErrors errors, Validator validator, HttpServletRequest request){
	
	String str1 = null;
	
	if (isString(bean)){
	      str1 = (String)bean;
	}else {
	      str1 = ValidatorUtil.getValueAsString(bean, field.getProperty());
	}
	
	     
	boolean resultado = false;

    if (!(GenericValidator.isBlankOrNull(str1))) {
    	
        try {	            
        	resultado = W83bUtilidadesComunes.fncValidarTelefono(str1);	        	
        	
          }catch (Exception localException) {
        	  resultado = false;
        	  return resultado;
    	   }	    	 
    	   if (!resultado) {
    		   errors.add(field.getKey(), Q70ValidacionesCampo.getActionError(request, va, field));
    	   }
	   }   	
    return resultado;
}
	    
}